package com.gitee.wsl.ext.collection

import com.gitee.wsl.func.predicate.Predicate

import kotlin.collections.filter as kFilter

fun <T> Iterable<T>.filter(predicate: Predicate<T>) = kFilter{ predicate(it) }

fun <T: Any> Iterable<T?>.filterNotNullAllOrNull(): List<T>? {
    val res: MutableList<T> = ArrayList()
    for (value in this) {
        value ?: return null
        res.add(value)
    }
    return res
}

fun <T, R: Any> Iterable<T>.mapNotNullAllOrNull(f: (T) -> R?): List<R>? {
    val res: MutableList<R> = ArrayList()
    for (value in this) {
        val resValue = f(value)
        resValue ?: return null
        res.add(resValue)
    }
    return res
}

fun <T, R: Any> Iterable<T>.mapIndexedNotNullAllOrNull(f: (Int, T) -> R?): List<R>? {

    val res: MutableList<R> = ArrayList()
    for (entry in this.withIndex()) {
        val index = res.size
        val resValue = f(index, entry.value)
        resValue ?: return null
        res.add(resValue)
    }
    return res
}

fun <T, K: Any, V: Any> Iterable<T>.associateNotNullValues(f: (T) -> Pair<K, V?>): Map<K, V> {
    return mapNotNull {
        val (k, v) = f(it)
        if (v == null) null else (k to v)
    }.toMap()
}